<?php 
class indexation_models_admin extends CI_Model{
	public function __construct(){
		$this->load->database();
	}

	public function mot_commun($table='index_stop_words'){
		$query=$this->db->get($table);
		$tab=array();
		foreach ($query->result() as $row) 
			$tab[]=$row->word;
		return $tab;
	}

	public function mot_save($mot,$product_info_id,$poids){
		$query_mot=$this->db->get_where("index_product_word",array('word'=>$mot));
		//tester le mot qui exite dans tableau mot si il n'existe pas ajouter
		if ($query_mot->num_rows){
			$row = $query_mot->result() ;
			$id=$row[0]->id;
		}else{
			$sort_word=self::mbStringToArray($mot);
			$this->db->insert('index_product_word', array('word'=>$mot,'sort'=>implode('',$sort_word)));
			$id= $this->db->insert_id();
		}
		//ajouter le id de mot , poids , id de doccument
		
		$query_mot=$this->db->get_where("index_word",array('id_word'=>$id, 'id_doc'=>$product_info_id));
		
		if ($query_mot->num_rows){
			$row = $query_mot->result() ;
			$weight=$row[0]->weight+$poids;
			$this->db->update('index_word', array( 'weight'=>$weight), array('id_word' => $id,'id_doc'=>$product_info_id));
		}
		else {
			$this->db->insert('index_word', array('id_word'=>$id, 'id_doc'=>$product_info_id,'weight'=>$poids));
		}
	}

	private function mbStringToArray( $string){
		$string = htmlentities($string, ENT_NOQUOTES, 'utf-8');
	
		// remplacer les entités HTML pour avoir juste le premier caractères non accentués
		// Exemple : "&ecute;" => "e", "&Ecute;" => "E", "Ã " => "a" ...
		$string = preg_replace('#&([A-za-z])(?:acute|grave|cedil|circ|orn|ring|slash|th|tilde|uml);#', '\1', $string);
		// Supprimer tout le reste
		$string = preg_replace('#&[^;]+;#', '', $string);
		$sort_word=str_split($string);
		sort($sort_word);
		return $sort_word;
	}
}